package com.guomei.controller.exam;

import com.guomei.bean.PayRequest;
import com.guomei.bean.exam.domain.ExamEnroll;
import com.guomei.bean.exam.domain.ExamEnrollDTO;
import com.guomei.service.exam.ExamEnrollService;
import com.guomei.service.pay.PaymentStrategy;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考试报名控制器
 */
@RestController
@RequestMapping("/api1/examEnroll")
@Slf4j
public class ExamEnrollController {
    @Autowired
    private ExamEnrollService examEnrollService;

    @Autowired
    private PaymentStrategy paymentStrategy;

    /**
     * 获取报名信息
     * 
     * @return 报名列表
     */
    @PostMapping("/select")
    public Result<?> getAllEnrolls(@RequestBody ExamEnroll examEnroll) {
        log.info("获取报名信息");
        try {
            if (examEnroll == null || examEnroll.getPageNum() == null || examEnroll.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (examEnroll.getPageNum() <= 0 || examEnroll.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }

            // 强制只查询未删除的报名记录，忽略前端传入的 isDeleted 参数
            examEnroll.setIsDeleted(false);

            return examEnrollService.getByCondition(examEnroll);
        } catch (Exception e) {
            log.info("获取报名信息失败", e);
            return Result.fail("获取报名信息失败");
        }
    }

    /**
     * 根据ID获取报名详情
     * 
     * @param id 报名ID
     * @return 报名详情
     */
    @GetMapping("/detail/id/{id}")
    public Result<?> getEnrollDetail(@PathVariable Long id) {
        log.info("获取报名详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("报名ID不能为空");
            }
            ExamEnroll examEnroll = examEnrollService.getById(id);
            if (examEnroll == null) {
                return Result.fail("报名记录不存在");
            }
            return Result.success(examEnroll);
        } catch (Exception e) {
            log.info("获取报名详情失败", e);
            return Result.fail("获取报名详情失败");
        }
    }

    /**
     * 考试报名
     * 
     * @param examEnrollDTO 报名信息
     * @return 报名结果
     */
    @PostMapping("/enroll")
    public Result<?> enroll(@Valid @RequestBody ExamEnrollDTO examEnrollDTO, BindingResult result) {
        log.info("考试报名入参：{}", examEnrollDTO);
        // 实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return examEnrollService.enrollExam(examEnrollDTO);
        } catch (Exception e) {
            log.info("考试报名失败", e);
            return Result.error("报名失败");
        }
    }

    /**
     * 验证报名资格
     * 
     * @param examId 考试ID
     * @param userId 用户ID
     * @return 验证结果
     */
    @GetMapping("/validate/{examId}/{userId}")
    public Result<?> validateEnrollQualification(@PathVariable Long examId, @PathVariable Long userId) {
        log.info("验证报名资格，考试ID：{}，用户ID：{}", examId, userId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            return examEnrollService.validateEnrollQualification(examId, userId);
        } catch (Exception e) {
            log.info("验证报名资格失败", e);
            return Result.fail("验证失败");
        }
    }

    /**
     * 支付成功回调
     * 
     * @param orderNo 订单编号
     * @return 处理结果
     */
    @PostMapping("/paySuccess/{orderNo}")
    public Result<?> paySuccess(@PathVariable String orderNo) {
        log.info("支付成功回调，订单编号：{}", orderNo);
        try {
            if (orderNo == null) {
                return Result.fail("订单编号不能为空");
            }
            return examEnrollService.paySuccess(orderNo);
        } catch (Exception e) {
            log.info("支付成功处理失败", e);
            return Result.fail("处理失败");
        }
    }

    /**
     * 取消报名（根据考试ID和用户ID）
     * 
     * @param examId 考试ID
     * @param userId 用户ID
     * @return 取消结果
     */
    @PostMapping("/cancel/{examId}/{userId}")
    public Result<?> cancelEnroll(@PathVariable Long examId, @PathVariable Long userId) {
        log.info("取消报名，考试ID：{}，用户ID：{}", examId, userId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            return examEnrollService.cancelEnroll(examId, userId);
        } catch (Exception e) {
            log.info("取消报名失败", e);
            return Result.fail("取消失败");
        }
    }

    /**
     * 用户主动取消报名（根据订单号）
     * 
     * @param orderNo 订单编号
     * @return 取消结果
     */
    @PostMapping("/cancel/order/{orderNo}")
    public Result<?> cancelEnrollByOrderNo(@PathVariable String orderNo) {
        log.info("用户主动取消报名，订单号：{}", orderNo);
        try {
            return examEnrollService.cancelEnrollByOrderNo(orderNo);
        } catch (Exception e) {
            log.error("用户主动取消报名异常，订单号：{}", orderNo, e);
            return Result.fail("取消报名失败");
        }
    }

    /**
     * 根据考试ID获取报名列表
     * 
     * @param examId 考试ID
     * @return 报名列表
     */
    @GetMapping("/exam/{examId}")
    public Result<?> getEnrollsByExamId(@PathVariable Long examId) {
        log.info("根据考试ID获取报名列表，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            List<ExamEnroll> enrolls = examEnrollService.getByExamId(examId);
            return Result.success(enrolls);
        } catch (Exception e) {
            log.info("根据考试ID获取报名列表失败", e);
            return Result.fail("获取报名列表失败");
        }
    }

    /**
     * 根据用户ID获取报名列表
     * 
     * @param userId 用户ID
     * @return 报名列表
     */
    @GetMapping("/user/{userId}")
    public Result<?> getEnrollsByUserId(@PathVariable Long userId) {
        log.info("根据用户ID获取报名列表，用户ID：{}", userId);
        try {
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            List<ExamEnroll> enrolls = examEnrollService.getByUserId(userId);
            return Result.success(enrolls);
        } catch (Exception e) {
            log.info("根据用户ID获取报名列表失败", e);
            return Result.fail("获取报名列表失败");
        }
    }

    /**
     * 根据订单编号获取报名详情
     * 
     * @param orderNo 订单编号
     * @return 报名详情
     */
    @GetMapping("/order/{orderNo}")
    public Result<?> getEnrollByOrderNo(@PathVariable String orderNo) {
        log.info("根据订单编号获取报名详情，订单编号：{}", orderNo);
        try {
            if (orderNo == null) {
                return Result.fail("订单编号不能为空");
            }
            ExamEnroll examEnroll = examEnrollService.getByOrderNo(orderNo);
            if (examEnroll == null) {
                return Result.fail("报名记录不存在");
            }
            return Result.success(examEnroll);
        } catch (Exception e) {
            log.info("根据订单编号获取报名详情失败", e);
            return Result.fail("获取报名详情失败");
        }
    }

    /**
     * 统计考试报名人数
     * 
     * @param examId 考试ID
     * @return 报名人数
     */
    @GetMapping("/count/{examId}")
    public Result<?> countByExamId(@PathVariable Long examId) {
        log.info("统计考试报名人数，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            int count = examEnrollService.countByExamId(examId);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计考试报名人数失败", e);
            return Result.fail("统计失败");
        }
    }

    /**
     * 创建考试报名支付
     */
    @PostMapping("/pay")
    public Result<?> createExamEnrollPayment(@Valid @RequestBody PayRequest request, BindingResult result) {
        log.info("创建考试报名支付入参: {}", request);
        // 实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }

        try {
            // 验证订单号是否以EXAM开头
            if (request.getOutTradeNo() == null || !request.getOutTradeNo().startsWith("EXAM")) {
                return Result.fail("考试报名订单号格式错误，必须以EXAM开头");
            }

            // 验证考试报名记录是否存在
            ExamEnroll examEnroll = examEnrollService.getByOrderNo(request.getOutTradeNo());
            if (examEnroll == null) {
                return Result.fail("找不到对应的考试报名记录");
            }

            // 检查是否已支付
            if (examEnroll.getPayStatus() != null && examEnroll.getPayStatus() == 1) {
                return Result.fail("该考试报名已支付，无需重复支付");
            }

            // 调用支付服务
            return paymentStrategy.getPaymentService(request.getPayType()).createPayment(request);

        } catch (Exception e) {
            log.error("创建考试报名支付异常", e);
            return Result.fail("创建考试报名支付异常");
        }
    }

    /**
     * 查询考试报名支付状态
     */
    @GetMapping("/pay/status/{orderNo}")
    public Result<?> getExamEnrollPaymentStatus(@PathVariable String orderNo) {
        log.info("查询考试报名支付状态，订单号：{}", orderNo);
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.fail("订单号不能为空");
            }

            if (!orderNo.startsWith("EXAM")) {
                return Result.fail("订单号格式错误，必须以EXAM开头");
            }

            ExamEnroll examEnroll = examEnrollService.getByOrderNo(orderNo);
            if (examEnroll == null) {
                return Result.fail("找不到对应的考试报名记录");
            }

            // 返回支付状态信息
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("orderNo", orderNo);
            statusInfo.put("payStatus", examEnroll.getPayStatus());
            statusInfo.put("payType", examEnroll.getPayType());
            statusInfo.put("payTime", examEnroll.getPayTime());
            statusInfo.put("amount", examEnroll.getAmount());
            statusInfo.put("tradeNo", examEnroll.getTradeNo());
            statusInfo.put("wxNo", examEnroll.getWxNo());
            statusInfo.put("status", examEnroll.getStatus());
            statusInfo.put("isDeleted", examEnroll.getIsDeleted());

            return Result.success(statusInfo);

        } catch (Exception e) {
            log.error("查询考试报名支付状态失败", e);
            return Result.fail("查询支付状态失败");
        }
    }

    /**
     * 客户端删除报名记录（软删除）
     */
    @DeleteMapping("/delete/{orderNo}")
    public Result<?> deleteEnrollByUser(@PathVariable String orderNo) {
        log.info("客户端删除报名记录，订单号：{}", orderNo);
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.fail("订单号不能为空");
            }

            if (!orderNo.startsWith("EXAM")) {
                return Result.fail("订单号格式错误，必须以EXAM开头");
            }

            // 验证报名记录是否存在
            ExamEnroll examEnroll = examEnrollService.getByOrderNo(orderNo);
            if (examEnroll == null) {
                return Result.fail("报名记录不存在");
            }

            // 检查是否已经删除
            if (examEnroll.getIsDeleted() != null && examEnroll.getIsDeleted()) {
                return Result.fail("报名记录已删除");
            }

            // 调用软删除服务
            boolean success = examEnrollService.softDeleteEnroll(orderNo);
            if (success) {
                log.info("客户端删除报名记录成功，订单号：{}", orderNo);
                return Result.success("删除报名记录成功");
            } else {
                log.error("客户端删除报名记录失败，订单号：{}", orderNo);
                return Result.fail("删除报名记录失败");
            }

        } catch (Exception e) {
            log.error("客户端删除报名记录异常，订单号：{}", orderNo, e);
            return Result.fail("删除报名记录失败");
        }
    }

    @GetMapping("/detail/order/{orderNo}")
    public Result<?> getEnrollDetail(@PathVariable String orderNo) {
        log.info("获取报名详情，订单号：{}", orderNo);
        try {
            return examEnrollService.getOrderDetail(orderNo);
        } catch (Exception e) {
            log.error("获取报名详情失败，订单号：{}", orderNo, e);
            return Result.fail("获取报名详情失败");
        }
    }

}
